package com.tencent.trtc.live;

import static com.tencent.liteav.device.TXDeviceManager.TXSystemVolumeType.TXSystemVolumeTypeMedia;
import static com.tencent.trtc.TRTCCloudDef.TRTC_APP_SCENE_LIVE;
import static com.tencent.trtc.TRTCCloudDef.TRTC_GSENSOR_MODE_DISABLE;
import static com.tencent.trtc.TRTCCloudDef.TRTC_VIDEO_RESOLUTION_1280_720;
import static com.tencent.trtc.TRTCCloudDef.TRTC_VIDEO_RESOLUTION_MODE_LANDSCAPE;
import static com.tencent.trtc.TRTCCloudDef.TRTC_VIDEO_RESOLUTION_MODE_PORTRAIT;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.basic.TRTCBaseActivity;
import com.tencent.liteav.TXLiteAVCode;
import com.tencent.liteav.device.TXDeviceManager;
import com.tencent.rtmp.ui.TXCloudVideoView;
import com.tencent.trtc.TRTCCloud;
import com.tencent.trtc.TRTCCloudDef;
import com.tencent.trtc.TRTCCloudListener;
import com.tencent.trtc.TRTCStatistics;
import com.tencent.trtc.debug.Constant;
import com.tencent.trtc.debug.GenerateTestUserSig;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * Room View of Interactive Live Video Streaming for Anchor
 * <p>
 * Features:
 * - Enter a room: {@link LiveAnchorActivity#enterRoom()}
 * - Exit a room: {@link LiveAnchorActivity#exitRoom()}
 * - Switch between the front and rear cameras: {@link LiveAnchorActivity#switchCamera()}
 * - Turn on/off the camera: {@link LiveAnchorActivity#muteVideo()}
 * - Turn on/off the mic: {@link LiveAnchorActivity#muteAudio()}
 * <p>
 * For more information, please see the integration document {https://cloud.tencent.com/document/product/647/43182}.
 */
public class LiveAnchorActivity extends TRTCBaseActivity implements View.OnClickListener {
    private static final String TAG = "LiveBaseActivity";
    private static final int DEFAULT_CAPACITY = 5;

    private TXCloudVideoView mTxcvvAnchorPreviewView;
    private SurfaceView mSurfaceView;
    private TXCloudVideoView mTxcvvAnchorPreviewView1;
    private Button mButtonSwitchCamera;
    private Button mButtonMuteVideo;
    private Button mButtonMuteAudio;
    private ImageView mButtonBack;
    private TextView mTextTitle;

    private TRTCCloud mTRTCCloud;
    private TXDeviceManager mTXDeviceManager;
    private TRTCCloudDef.TRTCParams mTRTCParams;
    private boolean mIsFrontCamera = true;
    private String mRoomId;
    private String mUserId;
    private List<String> mRemoteUidList;
    private List<LiveSubVideoView> mRemoteViewList;
    private boolean mMuteVideoFlag = true;
    private boolean mMuteAudioFlag = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.live_activity_anchor);
        getSupportActionBar().hide();
        handleIntent();

        mTRTCCloud = TRTCCloud.sharedInstance(getApplicationContext());
        mTXDeviceManager = mTRTCCloud.getDeviceManager();
        mTRTCCloud.setListener(new TRTCCloudImplListener(LiveAnchorActivity.this));
        if (checkPermission()) {
            initView();
            enterRoom();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    protected void onUserLeaveHint() {
        super.onUserLeaveHint();
    }

    @Override
    public void onPictureInPictureModeChanged(boolean isInPictureInPictureMode) {
        super.onPictureInPictureModeChanged(isInPictureInPictureMode);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        exitRoom();
    }


    private void handleIntent() {
        Intent intent = getIntent();
        if (null != intent) {
            if (intent.getStringExtra(Constant.USER_ID) != null) {
                mUserId = intent.getStringExtra(Constant.USER_ID);
            }
            if (intent.getStringExtra(Constant.ROOM_ID) != null) {
                mRoomId = intent.getStringExtra(Constant.ROOM_ID);
            }
        }
    }

    protected void initView() {
        mButtonBack = findViewById(R.id.iv_back);
        mTextTitle = findViewById(R.id.tv_room_number);
        mButtonMuteVideo = findViewById(R.id.btn_mute_video);
        mButtonMuteAudio = findViewById(R.id.btn_mute_audio);
        mButtonSwitchCamera = findViewById(R.id.live_btn_switch_camera);
        mTxcvvAnchorPreviewView = findViewById(R.id.live_cloud_view_main);
        mSurfaceView = findViewById(R.id.surfaceView);

        if (!TextUtils.isEmpty(mRoomId)) {
            mTextTitle.setText(getString(R.string.live_roomid) + mRoomId);
        }

        mRemoteUidList = new ArrayList<>(DEFAULT_CAPACITY);
        mRemoteViewList = new ArrayList<>(DEFAULT_CAPACITY);

        mRemoteViewList.add((LiveSubVideoView) findViewById(R.id.live_cloud_view_2));
        mRemoteViewList.add((LiveSubVideoView) findViewById(R.id.live_cloud_view_3));
        mRemoteViewList.add((LiveSubVideoView) findViewById(R.id.live_cloud_view_4));
        mRemoteViewList.add((LiveSubVideoView) findViewById(R.id.live_cloud_view_5));
        mRemoteViewList.add((LiveSubVideoView) findViewById(R.id.live_cloud_view_6));

        mButtonBack.setOnClickListener(this);
        mTRTCCloud.setListener(new TRTCCloudImplListener(LiveAnchorActivity.this));
        for (int index = 0; index < mRemoteViewList.size(); index++) {
            mRemoteViewList.get(index).setLiveSubViewListener(new LiveSubViewListenerImpl(index));
        }
        mButtonMuteVideo.setOnClickListener(this);
        mButtonMuteAudio.setOnClickListener(this);
        mButtonSwitchCamera.setOnClickListener(this);
    }

    /**
     * 设置必要参数，进入trtc房间，开始推流
     */
    public void enterRoom() {
        mTRTCParams = new TRTCCloudDef.TRTCParams();
        mTRTCParams.sdkAppId = GenerateTestUserSig.SDKAPPID;
        mTRTCParams.userId = mUserId;
        mTRTCParams.roomId = Integer.parseInt(mRoomId);
        mTRTCParams.userSig = GenerateTestUserSig.genTestUserSig(mTRTCParams.userId);
        mTRTCParams.role = TRTCCloudDef.TRTCRoleAnchor;
        mTRTCCloud.startLocalPreview(mIsFrontCamera, mTxcvvAnchorPreviewView);
        // 编码码率18kbps
        mTRTCCloud.startLocalAudio(TRTCCloudDef.TRTC_AUDIO_QUALITY_SPEECH);
        // 编码码率128kbps
//        mTRTCCloud.startLocalAudio(TRTCCloudDef.TRTC_AUDIO_QUALITY_MUSIC);
        // 如果没有设置音频类型（通话音量和媒体音量），默认跟startLocalAudio 的音频类型一致，如果设置了音频类型，会改变音频类型，且startLocalAudio的编码率不受影响，
        mTXDeviceManager.setSystemVolumeType(TXSystemVolumeTypeMedia);
//        mTRTCCloud.setGSensorMode(TRTCCloudDef.TRTC_GSENSOR_MODE_);

        // 采集设备旋转后，发出去的视频流，画布旋转，画面不动（画面内容预览和播放的画面四角一致），视频内容始终朝上，不缩放
        // 使得setVideoEncoderParam  videoResolutionMode无效
//        mTRTCCloud.setGravitySensorAdaptiveMode(TRTCCloudDef.TRTC_GRAVITY_SENSOR_ADAPTIVE_MODE_FIT_WITH_BLACK_BORDER);

        // 采集设备旋转后，发出去的视频流，画布不动 ，画面旋转（预览和播放的画面内容方向、分辨率不一致，被裁剪），视频内容始终朝上，放大 缩小
        // 使得setVideoEncoderParam  videoResolutionMode有效
        mTRTCCloud.setGravitySensorAdaptiveMode(TRTCCloudDef.TRTC_GRAVITY_SENSOR_ADAPTIVE_MODE_FILL_BY_CENTER_CROP);

        // 采集设备旋转后，发出去的视频流，画布不动，画面不缩放，进行旋转。（画面内容预览和播放的画面四角一致）
        // 使得setVideoEncoderParam  videoResolutionMode 有效
//        mTRTCCloud.setGravitySensorAdaptiveMode(TRTCCloudDef.TRTC_GRAVITY_SENSOR_ADAPTIVE_MODE_DISABLE);
//        todo 隐藏接口，设置采集分辨率为横屏
//        TUIPlayerShortVideo i = new TuiplayerShortVideo();

        //设置大流
        //
        TRTCCloudDef.TRTCVideoEncParam bigVideoEncParam = new TRTCCloudDef.TRTCVideoEncParam();
        bigVideoEncParam.videoFps = 15;
//        bigVideoEncParam.videoBitrate = TRTCCloudDef.TRTC_VIDEO_RESOLUTION_1280_720;
//        bigVideoEncParam.videoResolutionMode = TRTC_VIDEO_RESOLUTION_MODE_LANDSCAPE;
        // 从当前画面中心，裁剪出符合分辨率的画面
        bigVideoEncParam.videoResolution = TRTCCloudDef.TRTC_VIDEO_RESOLUTION_1280_720;
        bigVideoEncParam.videoResolutionMode = TRTC_VIDEO_RESOLUTION_MODE_LANDSCAPE;
//        bigVideoEncParam.videoResolutionMode = TRTC_VIDEO_RESOLUTION_MODE_PORTRAIT;
        bigVideoEncParam.minVideoBitrate = 1500;
        bigVideoEncParam.videoBitrate = 1500;
        mTRTCCloud.setVideoEncoderParam(bigVideoEncParam);


//开启双流（小流）

//
//        TRTCCloudDef.TRTCVideoEncParam smallVideoEncParam = new TRTCCloudDef.TRTCVideoEncParam();
//        smallVideoEncParam.videoFps = 15;
//        smallVideoEncParam.videoResolution = TRTCCloudDef.TRTC_VIDEO_RESOLUTION_160_120;
//        smallVideoEncParam.videoResolutionMode = TRTC_VIDEO_RESOLUTION_MODE_LANDSCAPE;
//        bigVideoEncParam.minVideoBitrate = 1000;
//        bigVideoEncParam.videoBitrate = 1500;
//        int smallVideoStream = mTRTCCloud.enableEncSmallVideoStream(true, smallVideoEncParam);

        mTRTCCloud.enterRoom(mTRTCParams, TRTC_APP_SCENE_LIVE);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (id == R.id.btn_mute_video) {
            muteVideo();
        } else if (id == R.id.btn_mute_audio) {
            muteAudio();
        } else if (id == R.id.live_btn_switch_camera) {
            switchCamera();
        } else if (id == R.id.iv_back) {
            finish();
        }
    }

    protected void switchCamera() {
        if (mIsFrontCamera) {
            mIsFrontCamera = false;
            mButtonSwitchCamera.setText(getString(R.string.live_user_front_camera));
        } else {
            mIsFrontCamera = true;
            mButtonSwitchCamera.setText(getString(R.string.live_user_back_camera));
        }
        mTXDeviceManager.switchCamera(mIsFrontCamera);
    }

    private void muteVideo() {
        if (mMuteVideoFlag) {
            mMuteVideoFlag = false;
            mTRTCCloud.stopLocalPreview();
            mButtonMuteVideo.setText(getString(R.string.live_open_camera));
        } else {
            mMuteVideoFlag = true;
            mTRTCCloud.startLocalPreview(mIsFrontCamera, mTxcvvAnchorPreviewView);
            mButtonMuteVideo.setText(getString(R.string.live_close_camera));
        }
    }

    private void muteAudio() {
        if (mMuteAudioFlag) {
            mMuteAudioFlag = false;
            mTRTCCloud.muteLocalAudio(true);
            mButtonMuteAudio.setText(getString(R.string.live_open_mic));
        } else {
            mMuteAudioFlag = true;
            mTRTCCloud.muteLocalAudio(false);
            mButtonMuteAudio.setText(getString(R.string.live_close_mic));
        }
    }

    protected class TRTCCloudImplListener extends TRTCCloudListener {

        private WeakReference<LiveAnchorActivity> mContext;

        public TRTCCloudImplListener(LiveAnchorActivity activity) {
            super();
            mContext = new WeakReference<>(activity);
        }


        @Override
        public void onEnterRoom(long result) {
            super.onEnterRoom(result);
        }

        @Override
        public void onExitRoom(int reason) {
            super.onExitRoom(reason);
        }


        @Override
        public void onConnectionLost() {
            super.onConnectionLost();
        }

        @Override
        public void onTryToReconnect() {
            super.onTryToReconnect();
        }

        @Override
        public void onConnectionRecovery() {
            super.onConnectionRecovery();
        }

        @Override
        public void onRemoteUserEnterRoom(String userId) {

        }

        @Override
        public void onRemoteUserLeaveRoom(String userId, int reason) {

        }

        @Override
        public void onUserVideoAvailable(String userId, boolean available) {
            int index = mRemoteUidList.indexOf(userId);
            Log.d(TAG, "onUserVideoAvailable index " + index + ", available " + available + " userId " + userId);
            if (available) {
                if (index == -1 && !userId.equals(mRoomId)) {
                    mRemoteUidList.add(userId);
                    refreshRemoteVideoViews();
                }
            } else {
                if (index != -1 && !userId.equals(mRoomId)) {
                    mTRTCCloud.stopRemoteView(userId, TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG);
                    mRemoteUidList.remove(index);
                    refreshRemoteVideoViews();
                }
            }
        }


        @Override
        public void onError(int errCode, String errMsg, Bundle extraInfo) {
            Log.d(TAG, "sdk callback onError");
            LiveAnchorActivity activity = mContext.get();
            if (activity != null) {
                Toast.makeText(activity, "onError: " + errMsg + "[" + errCode + "]", Toast.LENGTH_SHORT).show();
                if (errCode == TXLiteAVCode.ERR_ROOM_ENTER_FAIL) {
                    activity.exitRoom();
                }
            }
        }

        private void refreshRemoteVideoViews() {
            for (int i = 0; i < mRemoteViewList.size(); i++) {
                if (i < mRemoteUidList.size()) {
                    String remoteUid = mRemoteUidList.get(i);
                    mRemoteViewList.get(i).setVisibility(View.VISIBLE);
                    // Start displaying the video screen of user userId
                    mTRTCCloud.startRemoteView(remoteUid, TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG,
                            mRemoteViewList.get(i).getVideoView());
                } else {
                    mRemoteViewList.get(i).setVisibility(View.GONE);
                }
            }
        }

        @Override
        public void onCameraDidReady() {
            super.onCameraDidReady();
        }

        @Override
        public void onStatistics(TRTCStatistics statistics) {
            super.onStatistics(statistics);
            // 打印statistics.localArray 的每个字段
            TRTCStatistics.TRTCLocalStatistics localStatistics = statistics.localArray.get(0);

            Log.d(TAG, "onStatistics:  localStatistics = " + localStatistics.videoBitrate);

        }
    }

    protected class LiveSubViewListenerImpl implements LiveSubVideoView.LiveSubViewListener {

        private int mIndex;

        public LiveSubViewListenerImpl(int index) {
            mIndex = index;
        }

        @Override
        public void onMuteRemoteAudioClicked(View view) {
            boolean isSelected = view.isSelected();
            if (!isSelected) {
                mTRTCCloud.muteRemoteAudio(mRemoteUidList.get(mIndex), true);
                view.setBackground(getResources().getDrawable(R.mipmap.live_subview_sound_mute));
            } else {
                mTRTCCloud.muteRemoteAudio(mRemoteUidList.get(mIndex), false);
                view.setBackground(getResources().getDrawable(R.mipmap.live_subview_sound_unmute));
            }
            view.setSelected(!isSelected);
        }

        @Override
        public void onMuteRemoteVideoClicked(View view) {
            boolean isSelected = view.isSelected();
            if (!isSelected) {
                mTRTCCloud.stopRemoteView(mRemoteUidList.get(mIndex), TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG);
                mRemoteViewList.get(mIndex).getMuteVideoDefault().setVisibility(View.VISIBLE);
                view.setBackground(getResources().getDrawable(R.mipmap.live_subview_video_mute));
            } else {
                mTRTCCloud.startRemoteView(mRemoteUidList.get(mIndex), TRTCCloudDef.TRTC_VIDEO_STREAM_TYPE_BIG,
                        mRemoteViewList.get(mIndex).getVideoView());
                view.setBackground(getResources().getDrawable(R.mipmap.live_subview_video_unmute));
                mRemoteViewList.get(mIndex).getMuteVideoDefault().setVisibility(View.GONE);
            }
            view.setSelected(!isSelected);
        }
    }

    protected void exitRoom() {
        if (mTRTCCloud != null) {
            mTRTCCloud.stopLocalAudio();
            mTRTCCloud.stopLocalPreview();
            mTRTCCloud.exitRoom();
            mTRTCCloud.setListener(null);
        }
        mTRTCCloud = null;
        TRTCCloud.destroySharedInstance();
    }

    @Override
    protected void onPermissionGranted() {
        initView();
        enterRoom();
    }
}
